import app from '@/app'
import Factory from './factory'
import { totalTicket } from '@/api/store/order'

class TicketFactory extends Factory {

  async getData(start, end, data) {
    const res = await totalTicket({ time: [start.unix(), end.unix()] })

    // 别名
    const name = {
      print: 'p',
      print_refund: 'pr',
      ticket: 't',
      ticket_refund: 'tr'
    }

    // 因为有多线程，就直接填充
    const total = { m: 0, c: 0 }
    res.forEach(item => {
      data[name[item.ticket]] = {
        m: item.money,
        c: item.count
      }
      total.m = app.math.add(total.m, item.money)
      total.c = app.math.add(total.c, item.count)
    })
    
    if(total.c) {
      data.total = total
    }
  }

  // 处理统计
  total() {
    // 统计字段
    const fields = ['p', 'pr', 't', 'tr', 'total']

    // 循环天
    this.day.forEach(data => {
      // 循环要统计的字段
      fields.forEach(field => {
        const value = data[field]
        if(value) {
          // 统计年
          this.year[field] = {
            m: app.math.add(this.year[field]?.m ?? 0, value.m),
            c: app.math.add(this.year[field]?.c ?? 0, value.c),
          }
          // 统计季度 
          this.quarter[data.id[0]][field] = {
            m: app.math.add(this.quarter[data.id[0]][field]?.m ?? 0, value.m),
            c: app.math.add(this.quarter[data.id[0]][field]?.c ?? 0, value.c),
          }
          // 统计月
          this.month[data.id[1]][field] = {
            m: app.math.add(this.month[data.id[1]][field]?.m ?? 0, value.m),
            c: app.math.add(this.month[data.id[1]][field]?.c ?? 0, value.c),
          }
        }
      })
    })
  }

  // 查询统计数据
  getTotal(type, index, day) {
    return {
      year: () => {
        return {
          data: this.year,
          list: this.month
        }
      },
      quarter: () => {
        const list = this.getDayList({ quarter: index })
        return {
          data: this.quarter[index],
          list,
          time: list.map(item => {
            return this.getDayTime(item).dateSmall()
          })
        }
      },
      month: () => {
        const list = this.getDayList({ month: index })
        return {
          data: this.month[index],
          list: list,
          time: list.map(item => {
            return this.getDayTime(item).dateSmall()
          })
        }
      },
      day: () => {
        const data = this.getDay(day.month(), day.day())
        return {
          data,
          list: [data],
          time: [this.getDayTime(data).dateSmall()]
        }
      }
    }[type]()
  }
}

export default TicketFactory